package iosr11.gbase.dao;

import iosr11.data.Entity;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import com.google.api.gbase.client.FeedURLFactory;
import com.google.api.gbase.client.GoogleBaseEntry;
import com.google.api.gbase.client.GoogleBaseFeed;
import com.google.api.gbase.client.GoogleBaseQuery;

public abstract class GenericDAOImpl<E extends Entity> implements GenericDAO<E> {
	private Logger log = Logger.getLogger("service-log");
	
	@Override
	public boolean add(E entity) {
		if (entity == null) {
			log.warning("pusty argument - przekazano null");
			return false;
		}
		GoogleBaseEntry entry = this.rewrite(entity);
		if (DAOLocatorImpl.getInstance().addRecord(entry)) {
			entity.setId(entry.getId());
			log.info("dodano nowy rekord o id: "+entry.getId());
			return true;
		}
		else {
			log.info("dodanie rekordu nie powiodlo sie");
			return false;
		}
	}

	@Override
	public boolean delete(E entity) {
		String id = entity.getId();
		log.info("usuwanie rekordu o id: "+id);
		return DAOLocatorImpl.getInstance().deleteRecord(id);
	}

	@Override
	public boolean exist(String id) {
		GoogleBaseEntry entry = DAOLocatorImpl.getInstance().getRecord(id);
		if (entry != null)
			return true;
		else
			return false;
	}

	@Override
	public List<E> getAll() {
		GoogleBaseQuery query = new GoogleBaseQuery(FeedURLFactory.getDefault()
				.getItemsFeedURL());
		GoogleBaseFeed feed = DAOLocatorImpl.getInstance().getGoogleBaseQueryResult(query);
		if (feed == null) {
			log.warning("brak elementow w bazie danych");
			return null;
		}
		List<E> result = new ArrayList<E>();
		for (GoogleBaseEntry entry : feed.getEntries()){
			if (this.checkType(entry)){
				if (this.rewrite(entry)!=null)
					result.add(this.rewrite(entry));
			}
		}
		log.info("znaleziono "+result.size()+" rekordow w bazie");
		return result;
	
	}

	@Override
	public E getByID(String id) {
		if (id==null){
			log.warning("brak id -null");
			return null;
		}
		GoogleBaseEntry entry = DAOLocatorImpl.getInstance().getRecord(id);
		if (entry == null) {
			log.warning("brak elementu o podanym id: "+id);
			return null;
		}
		if (checkType(entry)) {
			return this.rewrite(entry);
		} else {
			log.warning("znaleziony rekord jest innego typu - zle id: "+id);
			return null;
		}
	}

	@Override
	public Class<E> getEntityClass() {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean update(E entity) {
		GoogleBaseEntry entry = DAOLocatorImpl.getInstance().getRecord(entity.getId());
		if (entry==null){
			log.warning("bledny id - brak rekordu o pidanym id: "+entity.getId());
			return false;
		}
		log.info("wywolanie zmiany danych w bazie");
		return DAOLocatorImpl.getInstance().updateRecord(entry, this.rewrite(entity));
	}
	
}
